/**
 * Created by 小润 on 2017/5/20.
 */
$(document).ready(function (){
    var root_id, ajaxData, arrData;
   /* var fId = document.getElementById("fId").value;*/
    var userId=localStorage.getItem("userId");
    personId=localStorage.getItem("personId");
    pId=$(".pId").val();
    fId=$(".familyId").val();
    var data;

    if(fId=="0"){
        data={"userId":userId}
    }
    if(fId!="0"){
        data={"fId":fId,"personId":pId}
    }
    datas=data;
    url='/api/v1/familytree/newShowTree';
    getData(data,url);

    //这是自己测试用的数据
  /*  arrData = [
        { n: "沈青青", s: "M", vir:2,key: 1},
        { n: "沈静静", s: "F",ux:1,key: 2},
        { n: "沈飞", s: "M", m: 2, f: 1, vir:4,key: 3},
        { n: "沈茫茫", s: "F",m:2,ux:3,vir:1,key: 4}*/

        // {key:0 , n: "1", s: "M", m: -10, f: -11, ux: 1, a: ''},
        // {key: 1, n: "2", s: "F", m: -12, f: -13, a: ''},
        // {key: 2, n: "3", s: "M", m: 1, f: 0, ux: 3, a: []},
        // {key: 3, n: "4", s: "F", a: []},
        // {key: 4, n: "5", s: "M", m: 1, f: 0, ux: 5, a: []},
        // {key: 5, n: "Brooke", s: "F", a: []}
    //     {key: 6, n: "Claire", s: "F", m: 1, f: 0, a: []},
    //     {key: 7, n: "Carol", s: "F", m: 1, f: 0, a: []},
    //     {key: 8, n: "Chloe", s: "F", m: 1, f: 0, vir: 9, a: []},
    //     {key: 9, n: "Chris", s: "M", a: []}
    //     {key: 10, n: "Ellie", s: "F", m: 3, f: 2, a: []},
    //     {key: 11, n: "Dan", s: "M", m: 3, f: 2, a: []},
    //     {key: 12, n: "Elizabeth", s: "F", vir: 13, a: []},
    //     {key: 13, n: "David", s: "M", m: 5, f: 4, a: []},
    //     {key: 14, n: "Emma", s: "F", m: 5, f: 4, a: []}
        //{key: 15, n: "Evan", s: "M", m: 8, f: 9, a: []},
        //{key: 16, n: "ggg", s: "M", m: 8, f: 9, a: []},
        //{key: 17, n: "Eve", s: "F", vir: 16, a: []},
        //{key: 18, n: "Emily", s: "F", m: 8, f: 9},
        //{key: 19, n: "Fred", s: "M", m: 17, f: 16, a: []},
        //{key: 20, n: "Faith", s: "F", m: 17, f: 16, a: []},
        //{key: 21, n: "Felicia", s: "F", m: 12, f: 13, a: []},
        //{key: 22, n: "Frank", s: "M", m: 12, f: 13, a: []}
        //// "Aaron"'s ancestors
        //{key: -10, n: "Paternal Grandfather", s: "M", m: -33, f: -32, ux: -11, a: ["A", "S"]},
        //{key: -11, n: "Paternal Grandmother", s: "F", a: ["E", "S"]},
        //{key: -32, n: "Paternal Great", s: "M", ux: -33, a: ["F", "H", "S"]},
        ////{key: -33, n: "Paternal Great", s: "F", a: ["S"]},
        ////{key: -40, n: "Great Uncle", s: "M", m: -33, f: -32, a: ["F", "H", "S"]},
        ////{key: -41, n: "Great Aunt", s: "F", m: -33, f: -32, a: ["B", "I", "S"]},
        ////{key: -20, n: "Uncle", s: "M", m: -11, f: -10, a: ["A", "S"]},
        //// "Alice"'s ancestors
        //{key: -12, n: "Maternal Grandfather", s: "M", ux: -13, a: ["D", "L", "S"]},
        //{key: -13, n: "Maternal Grandmother", s: "F", m: -31, f: -30, a: ["H", "S"]},
        //{key: -21, n: "Aunt", s: "F", m: -13, f: -12, a: ["C", "I"]},
        //{key: -22, n: "Uncle", s: "M", ux: -21},
        //{key: -23, n: "Cousin", s: "M", m: -21, f: -22},
        //{key: -30, n: "Maternal Great", s: "M", ux: -31, a: ["D", "J", "S"]},
        //{key: -31, n: "Maternal Great", s: "F", m: -50, f: -51, a: ["B", "H", "L", "S"]},
        //{key: -42, n: "Great Uncle", s: "M", m: -30, f: -31, a: ["C", "J", "S"]},
        //{key: -43, n: "Great Aunt", s: "F", m: -30, f: -31, a: ["E", "G", "S"]},
        //{key: -50, n: "Maternal Great Great", s: "F", ux: -51, a: ["D", "I", "S"]},
        //{key: -51, n: "Maternal Great Great", s: "M", a: ["B", "H", "S"]}
/*    ];
    init(arrData)*/
});
//展示全部数据
//查看完整家族树
$('.more-btn').on('click',function(){
    $('#allTree').toggle();

    $('.all_list').on('click',function(){
        $('#myDiagramDiv').remove();
        $.ajax({
            url:'/api/v1/familytree/showTree',
            data:datas,
            type:'post',
            success:function (request) {
                console.log(request)
                ajaxData = request;
                var arr=ajaxData.nodes;
                var pid=ajaxData.pId;
                var arrData=[];
                /*arrData =data.nodes;*/
                for(var i=0;i<arr.length;i++){
                    //   alert(toString.call(JSON.parse(JSON.stringify(arr[i]))))
                    arrData.push(JSON.parse(JSON.stringify(arr[i])));
                }
                $(".pId").val(pid);
                console.log(arrData);
                $('#myDiagramDiv1').show();
                init1(arrData);
            },
            error:function (e) {
                console.log(e)
            }
        })
    })
})


function init(arrData) {
    console.log(arrData);
    if (window.goSamples) goSamples();  // init for these samples -- you don't need to call this
    var $ = go.GraphObject.make;
    myDiagram =
        $(go.Diagram, "myDiagramDiv",
            {
                initialAutoScale: go.Diagram.Uniform,
                initialContentAlignment: go.Spot.Center,
                "undoManager.isEnabled": true,
                // when a node is selected, draw a big yellow circle behind it
                nodeSelectionAdornmentTemplate: $(go.Adornment, "Auto",
                    {layerName: "Grid"},  // the predefined layer that is behind everything else
                    $(go.Shape, "Circle", {fill: "yellow", stroke: null}),
                    $(go.Placeholder)
                ),
                layout:  // use a custom layout, defined below
                    $(GenogramLayout, {direction: 90, layerSpacing: 30, columnSpacing: 10})
            });
    // named by the category value in the node data object

    myDiagram.nodeTemplateMap.add("M",  // male
        $(go.Node, "Vertical",
            {locationSpot: go.Spot.Center, locationObjectName: ""},
            $(go.Panel,
                {name: ""},
                {
                    //点击事件
                    // doubleClick: function (Node,e) {
                    //     var key = e.part.data.key;   //获取当前人的ID
                    //     console.log(e.part.data); //当前点击人员的信息
                    //     console.log(key);
                    //   //  getData();
                    //     window.location.href = "/h5/user/personal?personId="+key+"&url=0&familyId="+fId;//跳转到个人主页
                    //     //window.location.href = '../../html/myself/pasonnal-page.html?id='+key+'';//跳转到制指定的个人主页
                    // }
                    click: function (Node,e) {
                        var key = e.part.data.key;   //获取当前人的ID
                        console.log(e.part.data); //当前点击人员的信息
                        console.log(key);
                        if(pId == key){
                            window.location.href = "/h5/user/personal?personId="+key+"&url=0&familyId="+fId;//跳转到个人主页
                        }else {
                          window.location.href="/h5/family/tree?familyId="+fId+"&personId="+key;
                        }

                        //window.location.href = '../../html/myself/pasonnal-page.html?id='+key+'';//跳转到制指定的个人主页
                    }
                },
                $(go.Shape, "Rectangle",
                    {width: 45, height: 70, strokeWidth: 0, fill: "#efe", portId: ""}),

                //添加人物图片
                $(go.Picture,
                    {source: "/static/h5/images/family-tree-male.png", width: 45, height: 45}),
                $(go.Panel,
                    { // for each attribute show a Shape at a particular place in the overall square
                        itemTemplate: $(go.Panel,
                            $(go.Shape,
                                {stroke: null, strokeWidth: 0},
                                new go.Binding("fill", ""),
                                new go.Binding("geometry", ""))
                        ),
                        margin: 1
                    },
                    new go.Binding("itemArray", "a")
                )
            ),
            //修改文字信息
            $(go.TextBlock,
                {
                    font: "10px Helvetica, bold Arial, sans-serif", stroke: "#aaa", margin: -15,
                    textAlign: "center", maxSize: new go.Size(150, NaN)
                },
                new go.Binding("text", "n"))
        ));
    myDiagram.nodeTemplateMap.add("F",  // female
        $(go.Node, "Vertical",
            {locationSpot: go.Spot.Center, locationObjectName: ""},
            $(go.Panel,
                {name: ""},
                {
                    click: function (Node,e) {
                        var key = e.part.data.key;   //获取当前人的ID
                        console.log(e.part.data); //当前点击人员的信息
                        console.log(key);
                        if(pId == key){
                            window.location.href = "/h5/user/personal?personId="+key+"&url=0&familyId="+fId;//跳转到个人主页
                        }else {
                            window.location.href="/h5/family/tree?familyId="+fId+"&personId="+key;
                        }

                        //window.location.href = '../../html/myself/pasonnal-page.html?id='+key+'';//跳转到制指定的个人主页
                    }
                },
                $(go.Shape, "Rectangle",
                    {width: 45, height: 70, strokeWidth: 0, fill: "#efe", portId: ""}),
                $(go.Picture,
                    {source: "/static/h5/images/family-tree-female.png", width: 45, height: 45}),
                $(go.Panel,
                    { // for each attribute show a Shape at a particular place in the overall circle
                        itemTemplate: $(go.Panel,
                            $(go.Shape,
                                {stroke: null, strokeWidth: 0},
                                new go.Binding("fill", ""),
                                new go.Binding("geometry", ""))
                        ),
                        margin: 1
                    },
                    new go.Binding("itemArray", "a")
                )
            ),
            $(go.TextBlock,
                {
                    font: "10px Helvetica, bold Arial, sans-serif", stroke: "#aaa", margin: -15,
                    textAlign: "center", maxSize: new go.Size(150, NaN)
                },
                new go.Binding("text", "n"))
        ));
    // the representation of each label node -- nothing shows on a Marriage Link
    myDiagram.nodeTemplateMap.add("LinkLabel",
        $(go.Node, {selectable: false, width: 1, height: 1, fromEndSegmentLength: 20}));
    myDiagram.linkTemplate =  // for parent-child relationships
        $(go.Link,
            {
                routing: go.Link.Orthogonal, curviness: 15,
                layerName: "Background", selectable: false,
                fromSpot: go.Spot.Bottom, toSpot: go.Spot.Top
            },
            $(go.Shape, {strokeWidth: 1,stroke: "#FA942B"})
        );
    myDiagram.linkTemplateMap.add("Marriage",  // for marriage relationships
        $(go.Link,
            {selectable: false},
            $(go.Shape, {strokeWidth: 1, stroke: "#FA942B"})
        ));
    // n: name, s: sex, m: mother, f: father, ux: wife, vir: husband, a: attributes/markers
    //setupDiagram(myDiagram, arrData ,4/* focus on this person */);
    setupDiagram(myDiagram, arrData);
}
function init1(arrData) {
    console.log(arrData);
    if (window.goSamples) goSamples();  // init for these samples -- you don't need to call this
    var $ = go.GraphObject.make;
    myDiagram =
        $(go.Diagram, "myDiagramDiv1",
            {
                initialAutoScale: go.Diagram.Uniform,
                initialContentAlignment: go.Spot.Center,
                "undoManager.isEnabled": true,
                // when a node is selected, draw a big yellow circle behind it
                nodeSelectionAdornmentTemplate: $(go.Adornment, "Auto",
                    {layerName: "Grid"},  // the predefined layer that is behind everything else
                    $(go.Shape, "Circle", {fill: "yellow", stroke: null}),
                    $(go.Placeholder)
                ),
                layout:  // use a custom layout, defined below
                    $(GenogramLayout, {direction: 90, layerSpacing: 30, columnSpacing: 10})
            });
    // named by the category value in the node data object

    myDiagram.nodeTemplateMap.add("M",  // male
        $(go.Node, "Vertical",
            {locationSpot: go.Spot.Center, locationObjectName: ""},
            $(go.Panel,
                {name: ""},
                {
                    //点击事件
                    // doubleClick: function (Node,e) {
                    //     var key = e.part.data.key;   //获取当前人的ID
                    //     console.log(e.part.data); //当前点击人员的信息
                    //     console.log(key);
                    //   //  getData();
                    //     window.location.href = "/h5/user/personal?personId="+key+"&url=0&familyId="+fId;//跳转到个人主页
                    //     //window.location.href = '../../html/myself/pasonnal-page.html?id='+key+'';//跳转到制指定的个人主页
                    // }
                    click: function (Node,e) {
                        var key = e.part.data.key;   //获取当前人的ID
                        console.log(e.part.data); //当前点击人员的信息
                        console.log(key);
                        if(pId == key){
                            window.location.href = "/h5/user/personal?personId="+key+"&url=0&familyId="+fId;//跳转到个人主页
                        }else {
                            window.location.href="/h5/family/tree?familyId="+fId+"&personId="+key;
                        }

                        //window.location.href = '../../html/myself/pasonnal-page.html?id='+key+'';//跳转到制指定的个人主页
                    }
                },
                $(go.Shape, "Rectangle",
                    {width: 45, height: 70, strokeWidth: 0, fill: "#efe", portId: ""}),

                //添加人物图片
                $(go.Picture,
                    {source: "/static/h5/images/family-tree-male.png", width: 45, height: 45}),
                $(go.Panel,
                    { // for each attribute show a Shape at a particular place in the overall square
                        itemTemplate: $(go.Panel,
                            $(go.Shape,
                                {stroke: null, strokeWidth: 0},
                                new go.Binding("fill", ""),
                                new go.Binding("geometry", ""))
                        ),
                        margin: 1
                    },
                    new go.Binding("itemArray", "a")
                )
            ),
            //修改文字信息
            $(go.TextBlock,
                {
                    font: "10px Helvetica, bold Arial, sans-serif", stroke: "#aaa", margin: -15,
                    textAlign: "center", maxSize: new go.Size(150, NaN)
                },
                new go.Binding("text", "n"))
        ));
    myDiagram.nodeTemplateMap.add("F",  // female
        $(go.Node, "Vertical",
            {locationSpot: go.Spot.Center, locationObjectName: ""},
            $(go.Panel,
                {name: ""},
                {
                    click: function (Node,e) {
                        var key = e.part.data.key;   //获取当前人的ID
                        console.log(e.part.data); //当前点击人员的信息
                        console.log(key);
                        if(pId == key){
                            window.location.href = "/h5/user/personal?personId="+key+"&url=0&familyId="+fId;//跳转到个人主页
                        }else {
                            window.location.href="/h5/family/tree?familyId="+fId+"&personId="+key;
                        }

                        //window.location.href = '../../html/myself/pasonnal-page.html?id='+key+'';//跳转到制指定的个人主页
                    }
                },
                $(go.Shape, "Rectangle",
                    {width: 45, height: 70, strokeWidth: 0, fill: "#efe", portId: ""}),
                $(go.Picture,
                    {source: "/static/h5/images/family-tree-female.png", width: 45, height: 45}),
                $(go.Panel,
                    { // for each attribute show a Shape at a particular place in the overall circle
                        itemTemplate: $(go.Panel,
                            $(go.Shape,
                                {stroke: null, strokeWidth: 0},
                                new go.Binding("fill", ""),
                                new go.Binding("geometry", ""))
                        ),
                        margin: 1
                    },
                    new go.Binding("itemArray", "a")
                )
            ),
            $(go.TextBlock,
                {
                    font: "10px Helvetica, bold Arial, sans-serif", stroke: "#aaa", margin: -15,
                    textAlign: "center", maxSize: new go.Size(150, NaN)
                },
                new go.Binding("text", "n"))
        ));
    // the representation of each label node -- nothing shows on a Marriage Link
    myDiagram.nodeTemplateMap.add("LinkLabel",
        $(go.Node, {selectable: false, width: 1, height: 1, fromEndSegmentLength: 20}));
    myDiagram.linkTemplate =  // for parent-child relationships
        $(go.Link,
            {
                routing: go.Link.Orthogonal, curviness: 15,
                layerName: "Background", selectable: false,
                fromSpot: go.Spot.Bottom, toSpot: go.Spot.Top
            },
            $(go.Shape, {strokeWidth: 1,stroke: "#FA942B"})
        );
    myDiagram.linkTemplateMap.add("Marriage",  // for marriage relationships
        $(go.Link,
            {selectable: false},
            $(go.Shape, {strokeWidth: 1, stroke: "#FA942B"})
        ));
    // n: name, s: sex, m: mother, f: father, ux: wife, vir: husband, a: attributes/markers
    //setupDiagram(myDiagram, arrData ,4/* focus on this person */);
    setupDiagram(myDiagram, arrData);
}
// create and initialize the Diagram.model given an array of node data representing people
function setupDiagram(diagram, array) {
    diagram.model =
        go.GraphObject.make(go.GraphLinksModel,
            { // declare support for link label nodes
                linkLabelKeysProperty: "labelKeys",
                // this property determines which template is used
                nodeCategoryProperty: "s",
                // create all of the nodes for people
                nodeDataArray: array
            });
    setupMarriages(diagram);
    setupParents(diagram);
    setupFatherAndChild(diagram);
    setupMotherAndChild(diagram);
    //var node = diagram.findNodeForKey(focusId);
    //if (node !== null) {
    //    diagram.select(node);
    //    // remove any spouse for the person under focus:
    //    //node.linksConnected.each(function(l) {
    //    //  if (!l.isLabeledLink) return;
    //    //  l.opacity = 0;
    //    //  var spouse = l.getOtherNode(node);
    //    //  spouse.opacity = 0;
    //    //  spouse.pickable = false;
    //    //});
    //}
}
function findMarriage(diagram, a, b) {  // A and B are node keys
    var nodeA = diagram.findNodeForKey(a);
    var nodeB = diagram.findNodeForKey(b);
    if (nodeA !== null && nodeB !== null) {
        var it = nodeA.findLinksBetween(nodeB);  // in either direction
        while (it.next()) {
            var link = it.value;
            // Link.data.category === "Marriage" means it's a marriage relationship
            if (link.data !== null && link.data.category === "Marriage") return link;
        }
    }
    return null;
}
// now process the node data to determine marriages
function setupMarriages(diagram) {
    var model = diagram.model;
    var nodeDataArray = model.nodeDataArray;
    for (var i = 0; i < nodeDataArray.length; i++) {
        var data = nodeDataArray[i];
        var key = data.key;
        var uxs = data.ux;
        if (uxs !== undefined) {
            if (typeof uxs === "number") uxs = [uxs];
            for (var j = 0; j < uxs.length; j++) {
                var wife = uxs[j];
                if (key === wife) {
                    // or warn no reflexive marriages
                    continue;
                }
                var link = findMarriage(diagram, key, wife);
                if (link === null) {
                    // add a label node for the marriage link
                    var mlab = {s: "LinkLabel"};
                    model.addNodeData(mlab);
                    // add the marriage link itself, also referring to the label node
                    var mdata = {from: key, to: wife, labelKeys: [mlab.key], category: "Marriage"};
                    model.addLinkData(mdata);
                }
            }
        }
        var virs = data.vir;
        if (virs !== undefined) {
            if (typeof virs === "number") virs = [virs];
            for (var j = 0; j < virs.length; j++) {
                var husband = virs[j];
                if (key === husband) {
                    // or warn no reflexive marriages
                    continue;
                }
                var link = findMarriage(diagram, key, husband);
                if (link === null) {
                    // add a label node for the marriage link
                    var mlab = {s: "LinkLabel"};
                    model.addNodeData(mlab);
                    // add the marriage link itself, also referring to the label node
                    var mdata = {from: key, to: husband, labelKeys: [mlab.key], category: "Marriage"};
                    model.addLinkData(mdata);
                }
            }
        }
    }
}
// process parent-child relationships once all marriages are known
function setupParents(diagram) {
    var model = diagram.model;
    var nodeDataArray = model.nodeDataArray;
    for (var i = 0; i < nodeDataArray.length; i++) {
        var data = nodeDataArray[i];
        var key = data.key;
        var mother = data.m;
        var father = data.f;
        if (mother !== undefined && father !== undefined) {
            var link = findMarriage(diagram, mother, father);
            if (link === null) {
                continue;
            }
            var mdata = link.data;
            var mlabkey = mdata.labelKeys[0];
            var cdata = {from: mlabkey, to: key};
            myDiagram.model.addLinkData(cdata);
        }
    }
}
// process parent-child relationships once all marriages are known

function setupFatherAndChild(diagram) {
    var model = diagram.model;
    var nodeDataArray = model.nodeDataArray;
    for (var i = 0; i < nodeDataArray.length; i++) {
        var data = nodeDataArray[i];
        var key = data.key;
        var mother = data.m;
        var father = data.f;
        if (mother === undefined && father !== undefined) {
            var cdata = {from: father, to: key};
            myDiagram.model.addLinkData(cdata);
        }
    }
}

function setupMotherAndChild(diagram){
    var model = diagram.model;
    var nodeDataArray = model.nodeDataArray;
    for (var i = 0; i < nodeDataArray.length; i++) {
        var data = nodeDataArray[i];
        var key = data.key;
        var mother = data.m;
        var father = data.f;
        if (mother !== undefined && father === undefined) {
            var cdata = {from: mother, to: key};
            myDiagram.model.addLinkData(cdata);
        }
    }
}

// A custom layout that shows the two families related to a person's parents
function GenogramLayout() {
    go.LayeredDigraphLayout.call(this);
    this.initializeOption = go.LayeredDigraphLayout.InitDepthFirstIn;
    this.spouseSpacing = 30;  // minimum space between spouses
}
go.Diagram.inherit(GenogramLayout, go.LayeredDigraphLayout);
/** @override */
GenogramLayout.prototype.makeNetwork = function (coll) {
    // generate LayoutEdges for each parent-child Link
    var net = this.createNetwork();
    if (coll instanceof go.Diagram) {
        this.add(net, coll.nodes, true);
        this.add(net, coll.links, true);
    } else if (coll instanceof go.Group) {
        this.add(net, coll.memberParts, false);
    } else if (coll.iterator) {
        this.add(net, coll.iterator, false);
    }
    return net;
};
// internal method for creating LayeredDigraphNetwork where husband/wife pairs are represented
// by a single LayeredDigraphVertex corresponding to the label Node on the marriage Link
GenogramLayout.prototype.add = function (net, coll, nonmemberonly) {
    var multiSpousePeople = new go.Set();
    // consider all Nodes in the given collection
    var it = coll.iterator;
    while (it.next()) {
        var node = it.value;
        if (!(node instanceof go.Node)) continue;
        if (!node.isLayoutPositioned || !node.isVisible()) continue;
        if (nonmemberonly && node.containingGroup !== null) continue;
        // if it's an unmarried Node, or if it's a Link Label Node, create a LayoutVertex for it
        if (node.isLinkLabel) {
            // get marriage Link
            var link = node.labeledLink;
            var spouseA = link.fromNode;
            var spouseB = link.toNode;
            // create vertex representing both husband and wife
            var vertex = net.addNode(node);
            // now define the vertex size to be big enough to hold both spouses
            vertex.width = spouseA.actualBounds.width + this.spouseSpacing + spouseB.actualBounds.width;
            vertex.height = Math.max(spouseA.actualBounds.height, spouseB.actualBounds.height);
            vertex.focus = new go.Point(spouseA.actualBounds.width + this.spouseSpacing / 2, vertex.height / 2);
        } else {
            // don't add a vertex for any married person!
            // instead, code above adds label node for marriage link
            // assume a marriage Link has a label Node
            var marriages = 0;
            node.linksConnected.each(function (l) {
                if (l.isLabeledLink) marriages++;
            });
            if (marriages === 0) {
                var vertex = net.addNode(node);
            } else if (marriages > 1) {
                multiSpousePeople.add(node);
            }
        }
    }
    // now do all Links
    it.reset();
    while (it.next()) {
        var link = it.value;
        if (!(link instanceof go.Link)) continue;
        if (!link.isLayoutPositioned || !link.isVisible()) continue;
        if (nonmemberonly && link.containingGroup !== null) continue;
        // if it's a parent-child link, add a LayoutEdge for it
        if (!link.isLabeledLink) {
            var parent = net.findVertex(link.fromNode);  // should be a label node
            var child = net.findVertex(link.toNode);
            if (child !== null) {  // an unmarried child
                net.linkVertexes(parent, child, link);
            } else {  // a married child
                link.toNode.linksConnected.each(function (l) {
                    if (!l.isLabeledLink) return;  // if it has no label node, it's a parent-child link
                    // found the Marriage Link, now get its label Node
                    var mlab = l.labelNodes.first();
                    // parent-child link should connect with the label node,
                    // so the LayoutEdge should connect with the LayoutVertex representing the label node
                    var mlabvert = net.findVertex(mlab);
                    if (mlabvert !== null) {
                        net.linkVertexes(parent, mlabvert, link);
                    }
                });
            }
        }
    }
    while (multiSpousePeople.count > 0) {
        // find all collections of people that are indirectly married to each other
        var node = multiSpousePeople.first();
        var cohort = new go.Set();
        this.extendCohort(cohort, node);
        // then encourage them all to be the same generation by connecting them all with a common vertex
        var dummyvert = net.createVertex();
        net.addVertex(dummyvert);
        var marriages = new go.Set();
        cohort.each(function (n) {
            n.linksConnected.each(function (l) {
                marriages.add(l);
            })
        });
        marriages.each(function (link) {
            // find the vertex for the marriage link (i.e. for the label node)
            var mlab = link.labelNodes.first()
            var v = net.findVertex(mlab);
            if (v !== null) {
                net.linkVertexes(dummyvert, v, null);
            }
        });
        // done with these people, now see if there are any other multiple-married people
        multiSpousePeople.removeAll(cohort);
    }
};
// collect all of the people indirectly married with a person
GenogramLayout.prototype.extendCohort = function (coll, node) {
    if (coll.contains(node)) return;
    coll.add(node);
    var lay = this;
    node.linksConnected.each(function (l) {
        if (l.isLabeledLink) {  // if it's a marriage link, continue with both spouses
            lay.extendCohort(coll, l.fromNode);
            lay.extendCohort(coll, l.toNode);
        }
    });
};
/** @override */
GenogramLayout.prototype.assignLayers = function () {
    go.LayeredDigraphLayout.prototype.assignLayers.call(this);
    var horiz = this.direction == 0.0 || this.direction == 180.0;
    // for every vertex, record the maximum vertex width or height for the vertex's layer
    var maxsizes = [];
    this.network.vertexes.each(function (v) {
        var lay = v.layer;
        var max = maxsizes[lay];
        if (max === undefined) max = 0;
        var sz = (horiz ? v.width : v.height);
        if (sz > max) maxsizes[lay] = sz;
    });
    // now make sure every vertex has the maximum width or height according to which layer it is in,
    // and aligned on the left (if horizontal) or the top (if vertical)
    this.network.vertexes.each(function (v) {
        var lay = v.layer;
        var max = maxsizes[lay];
        if (horiz) {
            v.focus = new go.Point(0, v.height / 2);
            v.width = max;
        } else {
            v.focus = new go.Point(v.width / 2, 0);
            v.height = max;
        }
    });
    // from now on, the LayeredDigraphLayout will think that the Node is bigger than it really is
    // (other than the ones that are the widest or tallest in their respective layer).
};
/** @override */
GenogramLayout.prototype.commitNodes = function () {
    go.LayeredDigraphLayout.prototype.commitNodes.call(this);
    // position regular nodes
    this.network.vertexes.each(function (v) {
        if (v.node !== null && !v.node.isLinkLabel) {
            v.node.position = new go.Point(v.x, v.y);
        }
    });
    // position the spouses of each marriage vertex
    var layout = this;
    this.network.vertexes.each(function (v) {
        if (v.node === null) return;
        if (!v.node.isLinkLabel) return;
        var labnode = v.node;
        var lablink = labnode.labeledLink;
        // In case the spouses are not actually moved, we need to have the marriage link
        // position the label node, because LayoutVertex.commit() was called above on these vertexes.
        // Alternatively we could override LayoutVetex.commit to be a no-op for label node vertexes.
        lablink.invalidateRoute();
        var spouseA = lablink.fromNode;
        var spouseB = lablink.toNode;
        // prefer fathers on the left, mothers on the right
        if (spouseA.data.s === "F") {  // sex is female
            var temp = spouseA;
            spouseA = spouseB;
            spouseB = temp;
        }
        // see if the parents are on the desired sides, to avoid a link crossing
        var aParentsNode = layout.findParentsMarriageLabelNode(spouseA);
        var bParentsNode = layout.findParentsMarriageLabelNode(spouseB);
        if (aParentsNode !== null && bParentsNode !== null && aParentsNode.position.x > bParentsNode.position.x) {
            // swap the spouses
            var temp = spouseA;
            spouseA = spouseB;
            spouseB = temp;
        }
        spouseA.position = new go.Point(v.x, v.y);
        spouseB.position = new go.Point(v.x + spouseA.actualBounds.width + layout.spouseSpacing, v.y);
        if (spouseA.opacity === 0) {
            var pos = new go.Point(v.centerX - spouseA.actualBounds.width / 2, v.y);
            spouseA.position = pos;
            spouseB.position = pos;
        } else if (spouseB.opacity === 0) {
            var pos = new go.Point(v.centerX - spouseB.actualBounds.width / 2, v.y);
            spouseA.position = pos;
            spouseB.position = pos;
        }
    });
    // position only-child nodes to be under the marriage label node
    this.network.vertexes.each(function (v) {
        if (v.node === null || v.node.linksConnected.count > 1) return;
        var mnode = layout.findParentsMarriageLabelNode(v.node);
        if (mnode !== null && mnode.linksConnected.count === 1) {  // if only one child
            var mvert = layout.network.findVertex(mnode);
            var newbnds = v.node.actualBounds.copy();
            newbnds.x = mvert.centerX - v.node.actualBounds.width / 2;
            // see if there's any empty space at the horizontal mid-point in that layer
            var overlaps = layout.diagram.findObjectsIn(newbnds, function (x) {
                return x.part;
            }, function (p) {
                return p !== v.node;
            }, true);
            if (overlaps.count === 0) {
                v.node.move(newbnds.position);
            }
        }
    });
};
GenogramLayout.prototype.findParentsMarriageLabelNode = function (node) {
    var it = node.findNodesInto();
    while (it.next()) {
        var n = it.value;
        if (n.isLinkLabel) return n;
    }
    return null;
};

function getData(data,url) {
    $.ajax({
        type: "post",
        data:data,
        // ContentType:'application/json',
        url:url,
        success: function (data) {
            console.log(data)
            ajaxData = data;
            var arr=data.nodes;
            var pid=data.pId;
            var arrData=[];
            /*arrData =data.nodes;*/
            for(var i=0;i<arr.length;i++){
                //   alert(toString.call(JSON.parse(JSON.stringify(arr[i]))))
                arrData.push(JSON.parse(JSON.stringify(arr[i])));
            }
            $(".pId").val(pid);
            console.log(arrData);

            init(arrData);
        },
        error: function (msg) {
            //alert('请求失败');
            console.log(msg)
        }
    });
}
//添加了遮罩层
$('.search_columns').click(function(){
    $('#zhezhaoceng').show();
    $('.search_column').show();
});
$('#zhezhaoceng').click(function(){
    $(this).hide();
    $('.search_column').hide();
});
$('.search_cancle').click(function(){
    $('.search_column').hide();
    $('#zhezhaoceng').hide();
});
$(".seacher").on("click",select);

//展示所有人员
function select(){
    var ajaxData,string,allText;
    var links;
    var html = '';
    $('#memberList').html('');
    var data={
        "familyId":fId
    }
    $.ajax({
        type: "post",
        data:data,
        url: '/api/v1/familytree/selectAll',   //所有人员列表接口
        success: function (data) {
           console.log(data);
            $.each(data.list,function(key,value){
                var ul = $('<ul><li class="generation">第'+data.list[key].generation+'世</li></ul>');
                $.each(data.list[key].persons,function(key,value){
                    console.log(value.avatar);
                    if(value.avatar == null){
                        html+='<li class="name"><a href="/h5/user/personal?personId='+value.id+'&url=0&familyId='+fId+'"><img src="/static/h5/images/family-tree-male.png" class="head" alt=""/>'+value.familyName+value.name+'</a></li> '
                    }else {
                        html+='<li class="name"><a href="/h5/user/personal?personId='+value.id+'&url=0&familyId='+fId+'"><img src='+value.avatar+' class="head" alt=""/>'+value.familyName+value.name+'</a></li> '
                    }
                })
                ul.append(html);
                $('#memberList').append(ul)
                ul = '';
                html = '';
            })
            links = $('#memberList').find('li');
            //搜索框筛选人员
            function getLinkText(){
                var allText='';
                for(var i=0;i<links.length;i++)
                {
                    allText += links[i].innerText+',';
                }
                return allText;
            }
            allText = getLinkText();
            var eachLink = new Array();
            eachLink=allText.split(","); //字符分割
            var inputValLength = 0;
            var m;
            setInterval(function(){
                var inputVal = $('#seach-button').val();
                if(inputVal.length != inputValLength){
                    links.css("display","block");
                    console.log(inputVal.length)
                    console.log(inputValLength)
                    for(m=0;m<eachLink.length;m++){
                        if(inputVal == ''){
                            links.eq(m).css("display","block");
                        }else{
                            var flag = eachLink[m].indexOf(inputVal);
                            if(flag==-1){
                                links.eq(m).css("display","none");
                            }
                        }
                    }
                    inputValLength = inputVal.length;
                }
            },1000);
            $('#seach-button').on('change',function(){
                var inputVal = $(this).val();

            })
            return false;
        },
        error: function (msg) {
            //alert('请求失败');
            console.log(msg)
        }
    });
    return false;
}